package com.cmccgz.udacs_landlord_webapp.update;

import java.io.File;
import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.gmcc.gz.http_wmmp.bean.GetAppDetailBeanRep;
import com.gmcc.gz.http_wmmp.task.GetAppDetailTask;
import com.gmcc.gz.http_wmmp.task.TaskTypeFactory;

public class CheckUpdate {
    /**
     * 下载状态变化
     */
    public static final int DOWN_LOAD_OB = 0;
    /**
     * 下载成功
     */
    private static final int DOWN_LOAD_SUCCESSFUL = 1;
    /**
     * 过度进度条开始
     */
    private static final int DIALOG_START = 2;
    /**
     * 过度进度条结束
     */
    private static final int DIALOG_DISMISS = 3;

    private static CheckUpdate checkUpdate;

    ProgressDialog progressDialog, downLoadProgressDialog;

    private Handler handler;

    private DownloadObserver downloadObserver;

    DownloadManagerPro downloadManagerPro;

    private AppInfoBean appInfoBean;

    private String titleName;

    private Context context;

    private long downloadId;

    private boolean mIsNeedDialog;

    private void initHandler() {
        if (handler == null)
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {

                        case DOWN_LOAD_OB:// ob观察下载变化
                            getDownLoadInfo(CheckUpdate.this.context, downloadId);
                            break;
                        case DOWN_LOAD_SUCCESSFUL:// ob观察下载成功
                            downLoadProgressDialog.dismiss();
                            unregisterDownLoadOb(context);
                            PackageUtils.installNormal(context, context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + FileUtils.getAppName());
                            break;

                        case DIALOG_START:// 开始检查更新dialog

                            try {
                                if (progressDialog != null && !progressDialog.isShowing()) {
                                    progressDialog.show();
                                }
                            } catch (Throwable e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            break;
                        case DIALOG_DISMISS:// 检查更新dialog结束
                            try {
                                if (progressDialog != null && progressDialog.isShowing())
                                    progressDialog.dismiss();
                            } catch (Throwable e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            break;
                        case TaskTypeFactory.TYPE_GET_APP_LIST: // 获取 applist
                            // handleAppList(msg);
                            break;

                        case TaskTypeFactory.TYPE_GET_APP_DETAIL://

                            handleAppDetail(msg);
                            break;

                        case AppVersionUpdateUtil.checkAppUpdateWhat: // 检测更新返回

                            handleCheckUpdate(msg);
                            break;
                        default:
                            break;
                    }
                }
            };
    }

    private CheckUpdate() {

    }

    public static synchronized CheckUpdate getInstance() {
        if (checkUpdate == null) {
            checkUpdate = new CheckUpdate();
        }
        return checkUpdate;
    }

    public void dialogRecycle() {
        progressDialog = null;
    }

    /**
     * start checkUpdate
     *
     * @param context context
     */
    public void start(Activity context) {
        start(context, null, true);
    }

    /**
     * start checkUpdate
     *
     * @param context      context
     * @param isNeedDialog isNeedDialog
     */
    public void start(Activity context, boolean isNeedDialog) {
        start(context, null, isNeedDialog);
    }

    /**
     * start checkUpdate
     *
     * @param context      context
     * @param titleName    titleName
     * @param isNeedDialog isNeedDialog
     */
    public void start(Activity context, String titleName, boolean isNeedDialog) {
        this.context = context;
        this.titleName = titleName;
        this.mIsNeedDialog = isNeedDialog;
        initHandler();
        if (isNeedDialog) {

            checkUpdateDialog(context);
        }
        handler.sendEmptyMessage(DIALOG_START);
        // AppManagerSupport.getAppList(context, handler);

        AppVersionUpdateUtil.checkAppUpdate(handler, context);
    }

    /**
     * getDownLoadInfo
     *
     * @param context    context
     * @param downloadId downloadId下载返回id
     */
    private synchronized void getDownLoadInfo(Context context, long downloadId) {
        if (downloadManagerPro == null)
            return;
        int[] bytesAndStatus = downloadManagerPro.getBytesAndStatus(downloadId);

        if (bytesAndStatus[2] == DownloadManager.STATUS_SUCCESSFUL) {
            handler.sendEmptyMessage(DOWN_LOAD_SUCCESSFUL);
        }

        downLoadDialog(context, bytesAndStatus);

    }

    /**
     * downLoadDialog
     *
     * @param context context
     * @param bytes   bytes
     *                <p/>
     *                a int array with three elements
     *                <ul>
     *                <li>bytes[0] represents downloaded bytes, This will initially
     *                be -1.</li>
     *                <li>bytes[1] represents total bytes, This will initially be
     *                -1.</li>
     *                <li>bytes[2] represents download status, This will initially
     *                be 0.</li>
     *                </ul>
     */
    private void downLoadDialog(Context context, int... bytes) {
        try {
            if (downLoadProgressDialog == null) {

                downLoadProgressDialog = new ProgressDialog(context);
                downLoadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                downLoadProgressDialog.setTitle(R.string.app_check_warm_prompt);
                downLoadProgressDialog.setMessage(context.getString(R.string.app_check_downloading));
                downLoadProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        downloadManagerPro.pauseDownload(downloadId);
                        downLoadProgressDialog.dismiss();
                    }
                });
            }
            if (bytes[1] < 0) {
                downLoadProgressDialog.setIndeterminate(true);
                downLoadProgressDialog.setMax(0);
                downLoadProgressDialog.setProgress(0);
                downLoadProgressDialog.show();
            } else {
                downLoadProgressDialog.setIndeterminate(false);
                downLoadProgressDialog.setMax(bytes[1]);

                downLoadProgressDialog.setProgress(bytes[0]);

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * startDownLoad
     *
     * @param context context
     * @param apkUrl  apkUrl
     * @return downLoadId
     */
    private long startDownLoad(Context context, String apkUrl) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (downloadManagerPro == null) {
            downloadManagerPro = new DownloadManagerPro(downloadManager);
        }
        registerDownLoadOb(context);
        DownloadManagerPro.RequestPro requestPro = new DownloadManagerPro.RequestPro(Uri.parse(apkUrl));
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + FileUtils.getAppName());
        if (file.exists())
            file.delete();
        requestPro.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, FileUtils.getAppName());

        return downloadManager.enqueue(requestPro);

    }

    /**
     * registerDownLoadOb
     *
     * @param context context
     */
    private void registerDownLoadOb(Context context) {
        if (downloadObserver == null) {

            downloadObserver = new DownloadObserver(handler);
        }
        context.getContentResolver().registerContentObserver(DownloadManagerPro.CONTENT_URI, true, downloadObserver);
    }

    /**
     * unregisterDownLoadOb
     *
     * @param context context
     */
    private void unregisterDownLoadOb(Context context) {
        context.getContentResolver().unregisterContentObserver(downloadObserver);
    }

    // private void handleAppList(Message msg) {
    // GetAppListTask appListTask = (GetAppListTask) msg.obj;
    // if (appListTask.isSuccess) {
    // GetAppListBeanRep appListBeanRep = (GetAppListBeanRep)
    // appListTask.resData;
    //
    // // String xmlRep = appListTask.xmlResData; //xml
    // String appListJson = appListBeanRep.getApplist(); //
    // handleDate(context, appListJson, titleName);
    // } else {
    // if(progressDialog !=null&&progressDialog.isShowing()){
    //
    // progressDialog.dismiss();
    // ToastUtils.show(context, R.string.app_check_exception);
    // }
    // }
    // }

    // private void handleDate(Context context, String appListJson,
    // String titleName) {
    // // write Log to File
    // CrashManager.creatLogToFile(appListJson);
    // try {
    // appInfoBean = AppManagerSupport.getAppinfo(appListJson, titleName);
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // int locationVersion = PackageUtils.getAppVersionCode(context);
    //
    // if (appInfoBean != null
    // && Integer.valueOf(appInfoBean.getVersion())
    // > locationVersion
    // ) {
    // handler.sendEmptyMessage(DIALOG_DISMISS);
    // new AlertDialog.Builder(context).setIcon(R.drawable.dialog_icon_warn)
    // .setTitle(R.string.app_check_exist_update)
    // .setMessage(appInfoBean.getDesc())
    // .setPositiveButton(android.R.string.ok,
    // new OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog,
    // int which) {
    // downloadId = startDownLoad(
    // CheckUpdate.this.context,
    // appInfoBean.getUrl());
    //
    // dialog.dismiss();
    // }
    // })
    // .setNegativeButton(android.R.string.cancel,
    // new OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog,
    // int which) {
    // dialog.dismiss();
    // }
    // }).setCancelable(false).create().show();
    // } else {
    // if (progressDialog != null &&progressDialog.isShowing()) {
    //
    //
    // progressDialog.dismiss();
    // ToastUtils.show(GlobalContext.getInstance().getApplicationContext(),
    // context.getString(R.string.app_check_update_latest));
    // }
    // }
    // }

    private void handleAppDetail(Message msg) {
        GetAppDetailTask appDetailTask = (GetAppDetailTask) msg.obj;
        if (appDetailTask.isSuccess) {
            GetAppDetailBeanRep appDetailBeanRep = (GetAppDetailBeanRep) appDetailTask.resData;

            String xmlRep = appDetailTask.xmlResData; //
            String appDetailJson = appDetailBeanRep.getAppdetail(); //
        } else if (-1 == appDetailTask.rspCode) {
        } else {
            handler.sendEmptyMessage(DIALOG_DISMISS);
        }
    }

    /**
     * checkUpdateDialog
     *
     * @param context context
     */
    private void checkUpdateDialog(Context context) {

        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle(R.string.app_check_update);
        progressDialog.setIndeterminate(false);

        progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE, context.getString(android.R.string.ok), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                progressDialog.dismiss();
            }
        });
    }

    /**
     * handleCheckUpdate
     *
     * @param msg
     */
    private void handleCheckUpdate(Message msg) {
        appInfoBean = (AppInfoBean) msg.obj;
        if (0 == appInfoBean.getRetcode()) {
            handleeCheckUpdateResult(context, appInfoBean);
        } else {
            if (progressDialog != null && progressDialog.isShowing()) {

                progressDialog.dismiss();
                ToastUtils.show(context, R.string.app_check_exception);
            }
        }
    }

    /**
     * handleeCheckUpdateResult
     *
     * @param context
     * @param appInfoBean
     */
    private void handleeCheckUpdateResult(final Context context, final AppInfoBean appInfoBean) {
        // write Log to File
        if (appInfoBean != null && appInfoBean.getIfUpdate() == 1) {
            handler.sendEmptyMessage(DIALOG_DISMISS);
            final int mustUpdate = appInfoBean.getMustUpdate();
            final String version = appInfoBean.getVersion();
            if (mustUpdate == 1) {
                AlertDialog alertDialog = new AlertDialog.Builder(context).setIcon(R.mipmap.dialog_icon_warn).setTitle(R.string.app_check_must_update).setMessage(appInfoBean.getDesc()).setPositiveButton(android.R.string.ok, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        downloadId = startDownLoad(CheckUpdate.this.context, appInfoBean.getUrl());
                        dialog.dismiss();
                    }
                }).setCancelable(false).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            } else {
                if (!version.equals(AppConfig.getIgnoreVersion(context))) {
                    new AlertDialog.Builder(context).setIcon(R.mipmap.dialog_icon_warn).setTitle(R.string.app_check_exist_update).setMessage(appInfoBean.getDesc()).setPositiveButton(android.R.string.ok, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            downloadId = startDownLoad(CheckUpdate.this.context, appInfoBean.getUrl());

                            dialog.dismiss();
                        }
                    }).setNegativeButton(android.R.string.cancel, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setNeutralButton("忽略该版本", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            AppConfig.setIgnoreVersion(context, version);
                            ToastUtils.show(context, "已忽略该版本更新");
                        }
                    }).setCancelable(true).create().show();
                } else {
                    if (this.mIsNeedDialog) {
                        ToastUtils.show(context, "无版本更新");
                    }
                }
            }
        } else {
            if (progressDialog != null && progressDialog.isShowing()) {

                progressDialog.dismiss();
                ToastUtils.show(context, context.getString(R.string.app_check_update_latest));
            }
        }
    }

    /**
     * 打开其他应用
     *
     * @param context
     * @param packageName
     * @param launcherActivityName
     */
    public void openOtherApp(Context context, String packageName, String launcherActivityName, String downLoadURL) {
        if (PackageUtils.isInstalled(context, packageName)) {
            PackageUtils.openApp(context, packageName, launcherActivityName);
        } else {
            showCheckInstallDialog(context, downLoadURL);
        }

    }

    /**
     * 显示提示下载
     *
     * @param context
     */
    private void showCheckInstallDialog(Context context, final String downLoadURL) {
        AlertDialog dilog = new AlertDialog.Builder(context).setTitle("提示").setMessage("还没有安装此应用,请先下载安装").setPositiveButton("下载", new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                downloadId = startDownLoad(CheckUpdate.this.context, downLoadURL);
                appInfoBean = new AppInfoBean();
                appInfoBean.setUrl(downLoadURL);
                dialog.dismiss();
            }
        }).setNegativeButton("取消", null).create();
        dilog.show();

    }

    private String formatSize(int size) {
        String sizeStr = "";
        if (size > 1024 * 1024) {
            sizeStr = new DecimalFormat("0.00").format(size * 1.0 / 1024 / 1024) + "M";
        } else if (size > 1024) {
            sizeStr = new DecimalFormat("0.00").format(size * 1.0 / 1024) + "K";
        } else {
            sizeStr = size + "B";
        }

        return sizeStr;
    }
}
